package com.yxx.community.advice;

import com.alibaba.fastjson.JSON;
import com.yxx.community.dto.ResultDTO;
import com.yxx.community.exception.CustomizeErrorCode;
import com.yxx.community.exception.CustomizeException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 15:42 2020/2/5
 **/
@ControllerAdvice
public class CustomizeExceptionHandler {

  @ExceptionHandler(Exception.class)
  ModelAndView handle(Throwable e, Model model,
                      HttpServletRequest request,
                      HttpServletResponse response){
    String contentType = request.getContentType();
    if("application/json".equals(contentType)){
      //返回json
      ResultDTO resultDTO;
      if(e instanceof CustomizeException){
        resultDTO= ResultDTO.errorof((CustomizeException)e);
      }else{
        resultDTO= ResultDTO.errorof(CustomizeErrorCode.SYS_ERROR);
      }
      try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(resultDTO));
        writer.close();
      }catch (Exception ioe){

      }
      return null;
    }else{
      //返回error页面
      if(e instanceof CustomizeException){
        model.addAttribute("message",e.getMessage());
      }else{
        model.addAttribute("message",CustomizeErrorCode.SYS_ERROR.getMessage());
      }
      return new ModelAndView("error");
    }

  }
}
